package com.edgclub.edg.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.ali.auth.third.ui.context.CallbackContext;
import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.constants.AlibcConstants;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.AlibcTaokeParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.model.ResultType;
import com.alibaba.baichuan.android.trade.model.TradeResult;
import com.alibaba.baichuan.android.trade.page.AlibcBasePage;
import com.alibaba.baichuan.android.trade.page.AlibcDetailPage;
import com.alibaba.baichuan.android.trade.page.AlibcShopPage;
import com.edgclub.edg.R;
import com.edgclub.edg.activity.GzWebViewActivityTaobao;

import java.util.HashMap;
import java.util.Map;

/**
 * 频道切换
 */
public class YouZanWebFragment extends GzBaseFragment {

    private Activity mActivity;
    WebView webView = null;
    private String shopId = "156890702";//默认店铺id

    private LinearLayout main_back;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public static YouZanWebFragment newInstance(String text) {
        YouZanWebFragment f = new YouZanWebFragment();
        return f;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mActivity = getActivity();
        View rootView = inflater.inflate(R.layout.fragment_taobao_layout, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        showShop(webView);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (null != webView && webView.canGoBack()) {
                    webView.goBack();
                    return true;
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }

    private void initView(View view) {
        webView = (WebView) view.findViewById(R.id.webview);
        WebSettings settings = webView.getSettings();
//        // 自适应屏幕
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setJavaScriptEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);

        webView.getSettings().setJavaScriptEnabled(true);


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //上报onActivityResult，如果遗漏，会出现调用逻辑错误；
        CallbackContext.onActivityResult(requestCode, resultCode, data);
    }

    //如果使用自定义webview的时候，需要在activity加上以下代码
    public boolean onBackPressed() {
        if (null != webView && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return false;
    }

    @Override
    public void onDestroy() {
        AlibcTradeSDK.destory();
        super.onDestroy();
    }

    WebViewClient webViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("detail.htm") || url.equals("https://m.taobao.com/")) {
                Intent intent = new Intent(getActivity(), GzWebViewActivityTaobao.class);
                intent.putExtra("url", url);
                getActivity().startActivity(intent);
                return true;
            }
//			https://h5.m.taobao.com/awp/core/detail.htm?id=536893711255&wp_m=userDefineItem_956&wp_pk=shop/index_2889025942_32129315&from=inshop&wp_app=weapp
            return false;
        }
    };


    public void showShop(View view) {
        Map<String, String> exParams = new HashMap<>();
        exParams.put(AlibcConstants.ISV_CODE, "appisvcode");
        exParams.put("EDGAPP", "EDGAPPTB");//自定义参数部分，可任意增删改
        AlibcBasePage alibcBasePage = new AlibcShopPage(shopId.trim());
        AlibcShowParams alibcShowParams = new AlibcShowParams(OpenType.H5, false);
        AlibcTrade.show(getActivity(), webView, webViewClient, null, alibcBasePage, alibcShowParams, null, exParams, new AlibcTradeCallback() {
            @Override
            public void onFailure(int errCode, String errMsg) {
                Toast.makeText(getActivity(), "电商SDK出错,错误码=" + errCode + " / 错误消息=" + errMsg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onTradeSuccess(TradeResult tradeResult) {
                if (tradeResult.resultType.equals(ResultType.TYPECART)) {
                    //加购成功
                    Toast.makeText(getActivity(), "加购成功", Toast.LENGTH_SHORT).show();
                } else if (tradeResult.resultType.equals(ResultType.TYPEPAY)) {
                    //支付成功
                    Toast.makeText(getActivity(), "支付成功,成功订单号为" + tradeResult.payResult.paySuccessOrders, Toast.LENGTH_SHORT).show();
                }
            }
        });


//		//获取电商能力服务AliTradeService
//		IAliTradeService aliTradeService = AliTradeSDK.getService(IAliTradeService.class);
//		AliTradeShowParams aliTradeShowParams = new AliTradeShowParams(AliOpenType.H5, false);
//		//提供给三方传递配置参数
//		Map<String, String> exParams = new HashMap<>();
//		exParams.put(AliTradeConstants.ISV_CODE, "appisvcode");
//
//		if (null == aliTradeService) {
//			Toast.makeText(getActivity(), "无法获取tradeService",
//					Toast.LENGTH_SHORT).show();
//			return;
//		}
//		AliTradeBasePage aliTradeBasePage = new AliTradeShopPage(shopId.trim());
//		AliTradeSDK.setChannel("EDGAPP", "EDGAPPTB");
//		aliTradeService.show(getActivity(),webView,webViewClient,aliTradeBasePage, aliTradeShowParams, null, exParams , new AliTradeProcessCallback() {
//			@Override
//			public void onFailure(int errCode, String errMsg) {
//				Toast.makeText(getActivity(), "流程出错,错误码="+errCode+" ,错误信息="+errMsg, Toast.LENGTH_SHORT).show();
//				Log.d("errCode----",errCode+"----------"+errMsg);
//				//10010----------alipay支付失败，信息为：使用支付宝支付失败，支付宝错误码为 6001, 含义为用户中途取消
//			}
//
//			@Override
//			public void onTradeSuccess(AliTradeResult aliTradeResult) {
//				if(aliTradeResult.resultType == AliTradeResultType.TYPECART){
//					Toast.makeText(getActivity(), "加购成功", Toast.LENGTH_SHORT).show();
//				}else if(aliTradeResult.resultType == AliTradeResultType.TYPEPAY){
//					Toast.makeText(getActivity(), "支付成功,订单号为"+aliTradeResult.payResult.paySuccessOrders, Toast.LENGTH_SHORT).show();
//				}
//			}
//		});
    }


}
